package com.amt.olcacon.controller.location;

import com.amt.olcacon.db.DerbyConfig;
import com.amt.olcacon.vo.GlobalResponse;
import com.amt.olcacon.vo.request.LocationRequest;
import lombok.extern.slf4j.Slf4j;
import org.openlca.core.DataDir;
import org.openlca.core.database.LocationDao;
import org.openlca.core.model.Location;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * location api
 *
 * @Author: yangyusheng
 * @Date: 2025/05/28
 */
@Slf4j
@RestController
@RequestMapping("/olca/location")
public class LocationController {

    @PostMapping("/add")
    public GlobalResponse<Long> add(@RequestBody LocationRequest request) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);

        var dao = new LocationDao(db);
        Location location = Location.of(request.getName(), request.getCode());

        location.id = request.getId();
        location.refId = request.getRefId();
        location.latitude = request.getLatitude();
        location.longitude = request.getLongitude();

        // 持久化到数据库
        var result = dao.insert(location);
        db.close();

        return GlobalResponse.of(result.id);
    }

    @PostMapping("/update")
    public GlobalResponse<Long> update(@RequestBody LocationRequest request) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new LocationDao(db);

        Location location = dao.getForId(request.getId());

        location.name = request.getName();
        location.code = request.getCode();
        location.longitude = request.getLongitude();
        location.latitude = request.getLatitude();

        // 持久化到数据库
        var result = dao.update(location);
        db.close();

        return GlobalResponse.of(result.id);
    }

    @GetMapping("/delete/{id}")
    public GlobalResponse<String> delete(@PathVariable("id") String id) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        new LocationDao(db).delete(Long.parseLong(id));
        db.close();

        return GlobalResponse.success();
    }

    @GetMapping("/get/{refId}")
    public GlobalResponse<Location> get(@PathVariable("refId") String refId) {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new LocationDao(db);
        Location location = dao.getForRefId(refId);
        db.close();

        return GlobalResponse.of(location);
    }

    @GetMapping("/getAll")
    public GlobalResponse<List<Location>> getAll() {

        var db = DataDir.get().openDatabase(DerbyConfig.DBNAME);
        var dao = new LocationDao(db);
        List<Location> locations = dao.getAll();
        db.close();

        locations.forEach(location -> location.geodata = null);

        return GlobalResponse.of(locations);
    }

}
